<template>
  <div id="app">
    <div>
      <span>图书名称:</span>
      <input type="text" ref="mikasa"  v-model="name"/>
    </div>
    <div>
      <button :disabled="isdisabled" @click="addormodifyss">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>图书名称</th>
          <th>创建时间</th>
          <th>操作</th>
        </tr>

      <line-tr @modify-name="modifyname" :list="list"  :obj="obj" v-for="obj in list" :key="obj.id" @deleteupdate="deletbtnupdate"></line-tr>
      </table>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
import lineTr from './components/lineTr.vue'
axios.defaults.baseURL = 'http://liufusong.top:4000/'
export default {
  components: { lineTr },
  data () {
    return {
      list: [],
      name: '',
      isadd: true,
      id: ''

    }
  },
  created () {
    this.getList()
  },
  methods: {
    async  getList () {
      const res = await axios({
        url: 'books'
      })
      console.log(res)
      this.list = res.data
    },
    async addormodify () {
      console.log(this.name)
      const res = await axios({
        url: 'books',
        method: 'post',
        data: {
          name: this.name
        }
      })
      console.log(res)

      this.name = ''
      this.getList()
    },
    modifyname (name) {
      this.name = name
      const id = this.list.find(item => item.name === this.name).id
      this.id = id

      this.$refs.mikasa.focus()
      this.isadd = false
    },

    async modifyfn (id) {
      console.log(this.name)
      console.log(id)
      const res = await axios({
        url: 'books/' + id,
        method: 'PUT',
        data: {
          name: this.name
        }
      })
      console.log(res)

      this.name = ''
      this.isadd = true
      this.getList()
    },
    async  addormodifyss () {
      const res = await this.getbookexit()

      if (res.data.status === 2) {
        console.log(88888888888)
        if (this.isadd) {
          this.addormodify()
          console.log('添加')
        } else {
          this.modifyfn(this.id)
          console.log('修改')
        }
      } else {
        alert('用户名已存在')
      }
      return false
    },
    deletbtnupdate () {
      this.getList()
    },
    async  getbookexit () {
      const res = await axios({
        url: 'books/book/' + this.name
      })
      return res
    }

  },
  computed: {
    isdisabled () {
      return this.list.some(item => (item.name === this.name))
    }
  }
}
</script>
